﻿using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SCZS.Example.Core.ConsulExtend.ServerExtend
{
    /// <summary>
    /// gRPC---当下注册模式时心跳失败
    /// consul发起请求--服务响应--但是没收到
    /// </summary>
    public static class gRPCConsulRegiterExtend
    {
        /// <summary>
        /// 基于提供信息完成注册
        /// </summary>
        /// <param name="app"></param>
        /// <param name="consulClientOption"></param>
        /// <param name="consulRegisterOption"></param>
        /// <returns></returns>
        public static async Task UseGRPCConsul(this IApplicationBuilder app, ConsulClientOption consulClientOption, ConsulRegisterOption consulRegisterOption, IHostApplicationLifetime lifetime)
        {
            using (ConsulClient client = new ConsulClient(c =>
            {
                c.Address = new Uri($"http://{consulClientOption.IP}:{consulClientOption.Port}/");
                c.Datacenter = consulClientOption.Datacenter;
            }))
            {
                var agentService = new AgentServiceRegistration()
                {
                    ID = $"gRPC-{consulRegisterOption.IP}-{consulRegisterOption.Port}-{Guid.NewGuid()}",//唯一Id
                    Name = consulRegisterOption.GroupName,//组名称-Group
                    Address = consulRegisterOption.IP,
                    Port = consulRegisterOption.Port,
                    Tags = new string[] { consulRegisterOption.Tag },
                    Check = new AgentServiceCheck()//配置心跳检查的
                    {
                        Interval = TimeSpan.FromSeconds(consulRegisterOption.Interval),
                        Timeout = TimeSpan.FromSeconds(consulRegisterOption.Timeout),
                        DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(consulRegisterOption.DeregisterCriticalServiceAfter),
                        GRPC = $"{consulRegisterOption.IP}:{consulRegisterOption.Port}",//直接gRPC
                        GRPCUseTLS = false
                    }
                };
                await client.Agent.ServiceRegister(agentService);
                Console.WriteLine($"grpc://{consulRegisterOption.IP}:{consulRegisterOption.Port}完成注册");
                //应用程序终止时，取消注册
                lifetime.ApplicationStopping.Register(() =>
                {
                    client.Agent.ServiceDeregister(agentService.ID).Wait();
                });
            }
        }

    }
}
